﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using Grpc.Core;
using Grpc.Net.Client;
using Grpc.Net.ClientFactory;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using RSTAi.Platform.GrpcService.Common;
using RSTAi.Platform.GrpcService.Services;
using static RSTAi.Platform.GrpcService.Services.IJwtTokenServices;
using Microsoft.Extensions.Caching.Memory;
using RSTAi.Platform.Test.Common;
using System.Threading.Channels;
using Microsoft.AspNetCore.Authorization;
using Google.Protobuf.Collections;

namespace RSTAi.Platform.Test.Controllers
{
    
    [ApiController]
    [Route("[controller]")]
    public class HomeController : Controller
    {
        //private readonly ILogger<HomeController> _logger;
        /* private readonly IUserService.IUserServiceClient _userServiceClient;*/
        private readonly IJwtTokenServices.IJwtTokenServicesClient _jwtTokenServicesClient;
        private readonly IProductServices.IProductServicesClient _productServicesClient;
        private ILoggerFactory _loggerFactory;
        private IMemoryCache _memoryCache;
        private readonly string token_key = "token_key_11";
        public HomeController(
            /* IUserService.IUserServiceClient userServiceClient,*/
            IJwtTokenServices.IJwtTokenServicesClient jwtTokenServicesClient, 
            ILoggerFactory loggerFactory,IMemoryCache memoryCache,
            IProductServices.IProductServicesClient productServicesClient
            )
        {

            _loggerFactory = loggerFactory;
            _jwtTokenServicesClient = jwtTokenServicesClient;
            _productServicesClient = productServicesClient;
            _memoryCache = memoryCache;
        }

        /// <summary>
        /// 获取token
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public string Index()
        {

            TokenFrom jwtTokenFrom = new TokenFrom();
            jwtTokenFrom.StationId = "001";
            jwtTokenFrom.TimeStamp = DateTime.Now.ToString("yyyyMMddHHmmssfff");
            StringBuilder stringBuilder = new StringBuilder();
            stringBuilder.Append(jwtTokenFrom.StationId);
            stringBuilder.Append(jwtTokenFrom.TimeStamp);
            stringBuilder.Append(MD5Helper.Md5Key);
            jwtTokenFrom.Sign = MD5Helper.GetMD5(stringBuilder.ToString());
            var responeDto = _jwtTokenServicesClient.GetToken(jwtTokenFrom);
            if (responeDto != null && responeDto.IsSuccess)
            {

                _memoryCache.Set(token_key, responeDto.Token);
                return responeDto.Token;
            }
            return "失败!";
        }

       

        /// <summary>
        /// 新增商品
        /// </summary>
        /// <param name="addProductFrom"></param>
        /// <returns></returns>
        [HttpPost("AddProduct")]
        public ResponeProductDto AddProduct(AddProductFrom addProductFrom)
        {
            var headers = new Metadata();
            Object obj = _memoryCache.Get(token_key);
            string token = obj?.ToString() ?? "";
            headers.Add("authorization", token);
            var responeToolDto = _productServicesClient.AddProduct(addProductFrom, headers);

            return responeToolDto;
        }

        /// <summary>
        /// 获取商品列表
        /// </summary>
        /// <param name="productListFrom"></param>
        /// <returns></returns>
        [HttpPost("GetProductList")]
        public ResponeProductDto GetProductList(ProductListFrom productListFrom)
        {
            var headers = new Metadata();
            Object obj = _memoryCache.Get(token_key);
            string token = obj?.ToString() ?? "";
            headers.Add("authorization", token);
            var responeToolDto = _productServicesClient.GetProductList(productListFrom, headers);


            return responeToolDto;
        }

        /// <summary>
        /// 获取商品
        /// </summary>
        /// <param name="productFrom"></param>
        /// <returns></returns>
        [HttpPost("GetProduct")]
        public ResponeProductDto GetProduct(ProductFrom productFrom)
        {
            var headers = new Metadata();
            Object obj = _memoryCache.Get(token_key);
            string token = obj?.ToString() ?? "";
            headers.Add("authorization", token);
            var responeToolDto = _productServicesClient.GetProduct(productFrom, headers);


            return responeToolDto;
        }

        /// <summary>
        /// 删除商品
        /// </summary>
        /// <param name="deleteProductFrom"></param>
        /// <returns></returns>
        [HttpDelete("DeleteProduct")]
        public ResponeProductDto DeleteProduct(DeleteProductFrom deleteProductFrom)
        {
            var headers = new Metadata();
            Object obj = _memoryCache.Get(token_key);
            string token =  obj?.ToString() ?? "";
            headers.Add("authorization", token);
            var responeToolDto = _productServicesClient.DeleteProduct(deleteProductFrom, headers);


            return responeToolDto;
        }

        /// <summary>
        /// 添加商品流程
        /// </summary>
        /// <param name="addProductStepFrom"></param>
        /// <returns></returns>
        [HttpPost("AddProductStep")]
        public ResponeProductStepDto AddProductStep(AddProductStepFrom addProductStepFrom)
        {
            var headers = new Metadata();
            Object obj = _memoryCache.Get(token_key);
            string token = obj?.ToString() ?? "";
            headers.Add("authorization", token);
           
           var responeToolDto = _productServicesClient.AddProductStep(addProductStepFrom, headers);
            return responeToolDto;
        }


        /// <summary>
        /// 获取商品流程详细信息
        /// </summary>
        /// <param name="productStepFrom"></param>
        /// <returns></returns>
        [HttpPost("GetProductStep")]
        public ResponeProductStepDto GetProductStep(ProductStepFrom productStepFrom)
        {
            var headers = new Metadata();
            Object obj = _memoryCache.Get(token_key);
            string token = obj?.ToString() ?? "";
            headers.Add("authorization", token);
            var responeToolDto = _productServicesClient.GetProductStep(productStepFrom, headers);
            return responeToolDto;
        }


        /// <summary>
        /// 删除商品流程
        /// </summary>
        /// <param name="deleteProductStepFrom"></param>
        /// <returns></returns>
        [HttpDelete("DeleteProductStep")]
        public ResponeProductStepDto DeleteProductStep(DeleteProductStepFrom deleteProductStepFrom)
        {
            var headers = new Metadata();
            Object obj = _memoryCache.Get(token_key);
            string token = obj?.ToString() ?? "";
            headers.Add("authorization", token);
            var responeToolDto = _productServicesClient.DeleteProductStep(deleteProductStepFrom, headers);
            return responeToolDto;
        }

        /// <summary>
        /// 修改产品参数
        /// </summary>
        /// <param name="updateProductStepFrom"></param>
        /// <returns></returns>
        [HttpDelete("UpdateStepParameter")]
        public ResponeProductStepDto UpdateStepParameter(UpdateProductStepFrom updateProductStepFrom)
        {
            var headers = new Metadata();
            Object obj = _memoryCache.Get(token_key);
            string token = obj?.ToString() ?? "";
            headers.Add("authorization", token);
            var responeToolDto = _productServicesClient.UpdateStepParameter(updateProductStepFrom, headers);
            return responeToolDto;

        }


        /// <summary>
        /// 客户端流式处理
        /// </summary>
        /// <returns></returns>
        [HttpGet("GetProductToStream")]
        public async Task<List<ResponeProductDto>> GetProductToStream()
        {
            var result = new List<ResponeProductDto>();
            var cancel = new CancellationToken();
            var request = new ProductFrom { StationId = "01" };
            var headers = new Metadata();
            Object obj = _memoryCache.Get(token_key);
            string token = obj?.ToString() ?? "";
            headers.Add("authorization", token);
            var response = _productServicesClient.GetProductToStream(request, headers);
            while (await response.ResponseStream.MoveNext(cancel))
            {
                result.Add(response.ResponseStream.Current);
            }

            return result;
        }


        /// <summary>
        /// 服务端流式处理
        /// </summary>
        /// <param name="userIds"></param>
        /// <returns></returns>
        [HttpGet("GetStreamToProduct")]
        public async Task<ResponeProductDto> GetStreamToProduct()
        {
            var headers = new Metadata();
            Object obj = _memoryCache.Get(token_key);
            string token = obj?.ToString()??"";
            headers.Add("authorization", token);
            using var call = _productServicesClient.GetStreamToProduct(headers);
            var clientStream = call.RequestStream;
            var productFromList = new List<ProductFrom>
            {
                new ProductFrom {  StationId="01" },
                new ProductFrom {  StationId="03" },
                new ProductFrom {  StationId="03" },
                new ProductFrom {  StationId="04" },
            };
            //循环给服务端发送流
            foreach (var item in productFromList)
            {
                await clientStream.WriteAsync(item);
            }

            // 发送完成之后，告诉服务端发送完成
            await clientStream.CompleteAsync();
            // 接收返回结果，并返回
            var res = await call.ResponseAsync;
            return res;
        }



        /// <summary>
        /// 双向模式 客户端
        /// </summary>
        /// <returns></returns>
        [HttpGet("StreamToStream")]
        public async Task<List<ResponeProductDto>> StreamToStream()
        {
            var headers = new Metadata();
            Object obj = _memoryCache.Get(token_key);
            string token = obj?.ToString() ?? "";
            headers.Add("authorization", token);
            //模拟用户添加的数据
            var productFromList = new List<ProductFrom>
            {
                new ProductFrom {  StationId="01" },
                new ProductFrom {  StationId="03" },
                new ProductFrom {  StationId="03" },
                new ProductFrom {  StationId="04" },
            };

            using var call = _productServicesClient.GetStreamToStream(headers);
            var clientStream = call.RequestStream;
            //循环给服务端发送流
            foreach (var item in productFromList)
            {
                await clientStream.WriteAsync(item);
            }

            // 发送完成之后，告诉服务端发送完成
            await clientStream.CompleteAsync();


            var cancel = new CancellationToken();
            List<ResponeProductDto> dtoList = new List<ResponeProductDto>();
            // 接收返回结果，并返回
            while (await call.ResponseStream.MoveNext(cancel))
            {
                dtoList.Add(call.ResponseStream.Current);
            }

            return dtoList;
        }



    }
}
